package com.zhj.juc.demo7;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @PackageName:com.zhj.juc.demo7
 * @ClassName:Test3SynchronousQueue
 * @auter: 朱慧杰
 * @date:2020/7/24 0024 10:01
 **/
public class Test3SynchronousQueue {

    /**
     * 同步队列
     * 和其他BlockingQueue 不一样，SynchronousQueue 不存储元素
     * put 了一个元素必须先取出来
     * @param args
     */
    public static void main(String[] args) {
        SynchronousQueue synchronousQueue = new SynchronousQueue(); // 同步队列

        new Thread(()->{
            try {
                System.out.println(Thread.currentThread().getName() + "put 1");
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName() + "put 2");
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName() + "put 3");
                synchronousQueue.put("3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();

        new Thread(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(2);
                System.out.println(Thread.currentThread().getName() + "take" + synchronousQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T2").start();

    }

}
